package com.itheima.springbootwebtlias.aspect;

import com.itheima.springbootwebtlias.mapper.LoginLogMapper;
import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.EmpLoginLog;
import com.itheima.springbootwebtlias.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 记录登录日志的切面类
 */
@Slf4j
@Component
@Aspect
public class LoginLogAspect {

    @Autowired
    private LoginLogMapper loginLogMapper;


    // 切入点表达式：execution
    @Around("execution(* com.itheima.springbootwebtlias.controller.LoginController.login(com.itheima.springbootwebtlias.pojo.Emp))")
    // 通知类型：环绕通知
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable{
        // 记录登录日志：收集登录日志信息，添加到登录日志数据表中
        long start = System.currentTimeMillis();
        Object result = null;
        try {
            result = pjp.proceed();
        }catch (Exception e){
            result = Result.error(e.getMessage());
        }finally {   // 无论登录成功还是失败，都会将日志添加到登录日志表中去
            long end = System.currentTimeMillis();
            long costTime = end - start;

            // 获取令牌
            Result result1 = (Result) result;
            Map map = (Map) result1.getData();
            String token = "";
            if(map != null){
                token = (String) map.get("token");
            }

            // 获取登录结果
            int code = (Integer) result1.getCode();
            short isSuccess = (short) code;

            // 获取请求参数
            Emp emp = (Emp) pjp.getArgs()[0];

            // 1.定义登录日志对象，收集登录日志信息
            EmpLoginLog empLoginLog = new EmpLoginLog();
            empLoginLog.setUsername(emp.getUsername());
            empLoginLog.setPassword(emp.getPassword());
            empLoginLog.setLoginTime(LocalDateTime.now());
            empLoginLog.setIsSuccess(isSuccess);
            empLoginLog.setJwt(token);
            empLoginLog.setCostTime(costTime);

            // 2.调用登录日志的持久层接口，添加日志信息到登录日志表中
            loginLogMapper.insert(empLoginLog);
        }

        return result;
    }
}
